// pages/tabbar/datas/components/secondTab.js
import { SignUpModel } from "../../../../api/api-work/signUpModel.js"
import { DataModel } from "../../../../api/api-data/dataModel.js"
import { ClassModel } from "../../../../api/api-work/classModel.js"
import moment from "moment"
const dataModel = new DataModel()
const signUpModel = new SignUpModel()
const classModel = new ClassModel()

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    mainActiveIndex: 0,
    activeId: null,
    secondTree: [
      {
        text: '全部',
      },
      {
        text: '主班老师',
        children: []
      },
      {
        text: '班级',
        children: []
      },
      {
        text: '课程',
        children: []
      },
    ],
    radioType: "1", // 1: 按天 2：按月
    showStartDate: false,
    minDate: new Date(2020, 0, 1).getTime(),
    startDateLabel: moment().format('YYYY-MM-DD'),
    startDateValue: moment().valueOf(), // 转为毫秒级时间戳
    showEndDate: false,
    endDateLabel: moment().format('YYYY-MM-DD'),
    endDateValue: moment().valueOf(), // 转为毫秒级时间戳
    formatterDate(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    showStartMonth: false,
    startMonthLabel: moment().format('YYYY-MM'),
    startMonthValue: moment().valueOf(),
    showEndMonth: false,
    endMonthLabel: moment().format('YYYY-MM'),
    endMonthValue: moment().valueOf(),

    form: {
      teacher: "",// 主班老师
      classId: "", // 班级
      courseId: "", // 课程
      startDate: moment().format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
      type: "1" // 1： 日  2：月
    },
    cardDatas: []
  },

  pageLifetimes: {
    // 页面显示
    show: function () {
      // console.log("页面显示")
      // 获取主班老师
      this.getStaffPeopleList();
      // 获取班级
      this.getClassList()
      // 获取课程
      this.getCourseList()
      // 获取数据
      this.getOurseOrderCountAcademicData()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeData(title, current, type, lastWeek, lastYear, remark, unit = "") {

      let title1 = ""; // 同比
      let title2 = "" // 环比
      let tongbi = ""; // 同比数据
      let huanbi = ""; // 环比数据

      // 同比趋势：  0：正常 1：上升  2：下降
      let trend1 = (current - lastWeek) > 0 ? "1" : (current - lastWeek) == 0 ? '0' : "2";
      if (lastWeek <= 0) {
        tongbi = "-"
      }
      else {
        tongbi = parseFloat(
          (
            (Math.abs(current - lastWeek) * 100) /
            lastWeek
          ).toFixed(2)
        ) + "%"
      }
      // 环比趋势：  0：正常 1：上升  2：下降
      let trend2 = (current - lastYear) > 0 ? "1" : (current - lastYear) == 0 ? '0' : "2";
      if (lastYear <= 0) {
        huanbi = "-"
      }
      else {
        huanbi = parseFloat(
          (
            (Math.abs(current - lastYear) * 100) /
            lastYear
          ).toFixed(2)
        ) + "%"
      }
      if (type == 1) {
        // 按日
        title1 = "日同比";
        title2 = "日环比";
      }
      else {
        // 按月
        title1 = "月同比";
        title2 = "月环比";
      }

      if (unit == "%") {
        if (current != 0) {
          current = (current * 100).toFixed(2) + "%"
        }
        else {
          current = "0%"

        }
      }
      return {
        title,
        remark,
        current,
        title1,
        trend1,
        tongbi,
        title2,
        trend2,
        huanbi
      }
    },
    getOurseOrderCountAcademicData() {
      dataModel.getOurseOrderCountAcademicDataApi(this.data.form).then(result => {
        console.log("jj: ", this.data.mainActiveIndex)
        if (this.data.mainActiveIndex == 0) {
          let arr = [
            this.changeData("在读学员数", result.num, this.data.radioType, result.numYear, result.numWeek, "所选时间段最后一刻的在读学员数）"),
            this.changeData("老师授课出勤率", result.attendance, this.data.radioType, result.attendanceYear, result.attendanceWeek, "所选时间段最后一刻的在读学员数）", "%"),
            this.changeData("学员到课出勤率", result.studentAttendance, this.data.radioType, result.studentAttendanceYear, result.studentAttendanceWeek, "所选时间段内，点名人次（包含补课、除试听）/点名应到人次*100%", "%"),
            this.changeData("老师实授课时", result.classHour, this.data.radioType, result.classHourYear, result.classHourWeek, "所选时间段内，老师的授课课时数之和"),
            this.changeData("老师应授课时", result.specifyNumber, this.data.radioType, result.specifyNumberYear, result.specifyNumberWeek, "所选时间段内，老师的排课数之和"),
            this.changeData("总课消金额", result.consumption, this.data.radioType, result.consumptionYear, result.consumptionWeek, "所选时间段内，产生的所有课消金额之和"),
          ]
          this.setData({
            cardDatas: arr
          })
        }
        else {
          let arr = [
            this.changeData("老师授课出勤率", result.attendance, this.data.radioType, result.attendanceYear, result.attendanceWeek, "所选时间段最后一刻的在读学员数）"),
            this.changeData("学员到课出勤率", result.studentAttendance, this.data.radioType, result.studentAttendanceYear, result.studentAttendanceWeek, "所选时间段内，点名人次（包含补课、除试听）/点名应到人次*100%"),
            this.changeData("老师实授课时", result.classHour, this.data.radioType, result.classHourYear, result.classHourWeek, "所选时间段内，老师的授课课时数之和"),
            this.changeData("老师应授课时", result.specifyNumber, this.data.radioType, result.specifyNumberYear, result.specifyNumberWeek, "所选时间段内，老师的排课数之和"),
          ]
          this.setData({
            cardDatas: arr
          })
        }


      })
    },
    onClickNav({ detail = {} }) {
      if (detail.index == 0) {
        // 全部
        this.setData({
          mainActiveIndex: detail.index,
          activeId: "",
          "form.teacher": "",
          "form.classId": "",
          "form.courseId": "",
        });
        this.getOurseOrderCountAcademicData()
        this.selectComponent('#item').toggle();
      } else {
        this.setData({
          mainActiveIndex: detail.index,
        });
      }
    },
    onClickItem({ detail = {} }) {
      const activeId = this.data.activeId === detail.id ? null : detail.id;
      if (this.data.mainActiveIndex == 1) {
        // 主班老师
        this.setData({
          activeId: activeId,
          "form.teacher": activeId,
          "form.classId": "",
          "form.courseId": "",
        })
      }
      else if (this.data.mainActiveIndex == 2) {
        // 班级
        this.setData({
          activeId: activeId,
          "form.classId": activeId,
          "form.teacher": "",
          "form.courseId": "",
        })
      }
      else if (this.data.mainActiveIndex == 3) {
        // 课程
        this.setData({
          activeId: activeId,
          "form.courseId": activeId,
          "form.teacher": "",
          "form.classId": "",
        })
      }
      this.getOurseOrderCountAcademicData()
      this.selectComponent('#item').toggle();
    },
    // 获取主班老师
    getStaffPeopleList() {
      classModel.getStaffPeopleListApi({ isTeach: 1 }).then(res => {
        let arr = []
        if (res.length > 0) {
          res.forEach(item => {
            const obj = {
              text: item.label,
              id: item.value
            }
            arr.push(obj)
          })
        }
        this.setData({
          "secondTree[1].children": arr
        })
      })
    },
    // 获取班级
    getClassList() {
      classModel.getClassListApi({ pageNum: 1, pageSize: 9999 }).then(res => {
        if (res.rows && res.rows.length > 0) {
          let arr = []
          res.rows.forEach(item => {
            const obj = {
              text: item.name,
              id: item.id
            }
            arr.push(obj)
          })
          this.setData({
            "secondTree[2].children": arr
          })
        }
      })
    },
    // 获取学员创建人
    getCourseList() {
      signUpModel.getCourseListAPI({ pageNum: 1, pageSize: 9999, open: 1 }).then(res => {
        if (res.rows && res.rows.length > 0) {
          let arr = []
          res.rows.forEach(item => {
            arr.push({
              text: item.name,
              id: item.id
            })
          })
          this.setData({
            "secondTree[3].children": arr
          })
        }
      })
    },
    onRadioChange(e) {
      this.setData({
        radioType: e.detail
      })
    },
    // 选择开始日期
    tapStartDate() {
      this.setData({
        showStartDate: true
      })
    },
    onCloseStartDate() {
      this.setData({
        showStartDate: false
      })
    },
    chooseStartDate(e) {
      const diff = moment(moment(e.detail).format("YYYY-MM-DD")).diff(moment(this.data.endDateLabel), 'days')
      if (diff > 0) {
        wx.showToast({
          title: '开始日期不能大于结束日期',
          icon: "none",
          duration: 2000
        })
      }
      else {
        this.setData({
          startDateValue: e.detail,
          startDateLabel: moment(e.detail).format("YYYY-MM-DD"),
          showStartDate: false
        })

      }
    },
    // 选择结束日期
    tapEndDate() {
      this.setData({
        showEndDate: true
      })
    },
    onCloseEndDate() {
      this.setData({
        showEndDate: false
      })
    },
    chooseEndDate(e) {
      const diff = moment(moment(e.detail).format("YYYY-MM-DD")).diff(moment(this.data.startDateLabel), 'days')
      if (diff < 0) {
        wx.showToast({
          title: '结束日期不能小于开始日期',
          icon: "none",
          duration: 2000
        })
      }
      else {
        this.setData({
          endDateValue: e.detail,
          endDateLabel: moment(e.detail).format("YYYY-MM-DD"),
          showEndDate: false
        })
      }
    },
    confirmDate() {
      this.setData({
        "form.startDate": this.data.startDateLabel,
        "form.endDate": this.data.endDateLabel,
        "form.type": "1"
      })
      this.getOurseOrderCountAcademicData()
      this.selectComponent('#itemDate').toggle();
    },
    // 选择开始月份
    tapStartMonth() {
      this.setData({
        showStartMonth: true
      })
    },
    onCloseStartMonth() {
      this.setData({
        showStartMonth: false
      })
    },
    chooseStartMonth(e) {
      const diff = moment(moment(e.detail).format("YYYY-MM")).diff(moment(this.data.endMonthLabel), 'months')
      if (diff > 0) {
        wx.showToast({
          title: '开始月份不能大于结束月份',
          icon: "none",
          duration: 2000
        })

      }
      else {
        this.setData({
          startMonthValue: e.detail,
          startMonthLabel: moment(e.detail).format("YYYY-MM"),
          showStartMonth: false
        })
      }
    },
    // 选择结束月份
    tapEndMonth() {
      this.setData({
        showEndMonth: true
      })
    },
    onCloseEndMonth() {
      this.setData({
        showEndMonth: false
      })
    },
    chooseEndMonth(e) {
      const diff = moment(moment(e.detail).format("YYYY-MM")).diff(moment(this.data.startMonthLabel), 'months')
      if (diff < 0) {
        wx.showToast({
          title: '结束月份不能小于开始月份',
          icon: "none",
          duration: 2000
        })
      }
      else {
        this.setData({
          endMonthValue: e.detail,
          endMonthLabel: moment(e.detail).format("YYYY-MM"),
          showEndMonth: false
        })
      }
    },
    confirmMonth() {
      this.setData({
        "form.startDate": this.data.startMonthLabel,
        "form.endDate": this.data.endMonthLabel,
        "form.type": "2"
      })
      this.getOurseOrderCountAcademicData()
      this.selectComponent('#itemDate').toggle();
    },
    showRemark(e) {
      wx.showToast({
        title: e.currentTarget.dataset.query.remark,
        icon: "none",
        duration: 2000
      })
    }
  }
})